<template>
  <div class="min-h-screen bg-gray-100">
    <Header />
    <div class="container mx-auto p-4">
      <!-- 加载状态 -->
      <div v-if="loading" class="text-center">加载中...</div>

      <!-- 错误提示 -->
      <div v-if="error" class="bg-red-100 p-4 rounded">{{ error }}</div>

      <!-- 内容展示 -->
      <div v-if="chapter" class="bg-white p-6 rounded shadow">
        <h1 class="text-3xl font-bold mb-4">{{ chapter.title }}</h1>

        <div class="content" v-html="formattedContent"></div>

        <!-- 导航按钮 -->
        <div class="mt-8 flex justify-between">
          <button
            @click="navigateToChapter(previousChapter)"
            :disabled="!previousChapter"
            class="px-4 py-2 bg-blue-500 text-white rounded disabled:bg-gray-300"
          >
            上一章
          </button>
          <button
            @click="$router.push(`/book/${bookId}`)"
            class="px-4 py-2 bg-gray-500 text-white rounded"
          >
            返回书籍
          </button>
          <button
            @click="navigateToChapter(nextChapter)"
            :disabled="!nextChapter"
            class="px-4 py-2 bg-blue-500 text-white rounded disabled:bg-gray-300"
          >
            下一章
          </button>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script>
import axios from "axios";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import showMessage from "@/utils/message.js";

export default {
  name: "ChapterRead",
  components: { Header, Footer },
  data() {
    return {
      chapter: null,
      chapters: [],
      loading: false,
      error: "",
      bookId: this.$route.params.id,
    };
  },
  watch: {
    // 监听路由变化
    "$route.params.chapter_id": {
      immediate: true, // 首次加载也执行
      handler() {
        this.loadChapter();
      },
    },
  },
  computed: {
    // 格式化内容计算属性
    formattedContent() {
      if (!this.chapter?.content) return "";

      // 分割段落（处理不同换行情况）
      const paragraphs = this.chapter.content
        .split(/(?:\n\s*){2,}/) // 匹配两个及以上换行（兼容含空格的换行）
        .filter((p) => p.trim()); // 过滤空段落

      // 处理段落内容
      return paragraphs
        .map((p) => {
          // 处理段落内换行为<br>，并添加首行空格占位
          return `<p>${p
            .trim()
            .replace(/\n/g, "<br>")
            .replace(/^/, "&emsp;&emsp;")}</p>`;
        })
        .join("");
    },
    // 计算上一章和下一章
    currentIndex() {
      return this.chapters.findIndex((ch) => ch.id === this.chapter?.id);
    },
    previousChapter() {
      return this.currentIndex > 0
        ? this.chapters[this.currentIndex - 1]
        : null;
    },
    nextChapter() {
      return this.currentIndex < this.chapters.length - 1
        ? this.chapters[this.currentIndex + 1]
        : null;
    },
  },
  async mounted() {
    await this.loadChapter();
    await this.loadChapterList();
  },
  methods: {
    // 加载当前章节内容
    async loadChapter() {
      this.loading = true;
      this.chapter = null; // 清空旧数据
      try {
        const res = await axios.get(
          `/api/article/${this.$route.params.chapter_id}/`
        );
        this.chapter = res.data;
      } catch (err) {
        this.error = "章节加载失败";
        showMessage(this.error, "error");
      } finally {
        this.loading = false;
      }
    },

    // 加载书籍所有章节列表（用于导航）
    async loadChapterList() {
      try {
        const res = await axios.get(`/api/article/?book=${this.bookId}`);
        this.chapters = res.data;
      } catch (err) {
        showMessage("无法获取章节列表", "error");
      }
    },

    // 跳转到指定章节
    navigateToChapter(chapter) {
      if (!chapter) return;
      this.$router.push(`/book/${this.bookId}/article/${chapter.id}`);
    },
  },
};
</script>

<style scoped>
/* 容器样式优化​ */
.bg-white {
  border-radius: 12px; /* 圆角加大 */
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05); /* 更柔和的阴影 */
  padding: 2.5rem; /* 增加内边距 */
}

/* 文本样式 */
h1 {
  font-family: "Noto Serif SC", serif; /* 使用衬线字体 */
  border-bottom: 2px solid #e2e8f0;
  padding-bottom: 1rem;
  margin-bottom: 2rem;
}

.content::v-deep {
  font-family: "Noto Serif SC", serif; /* 中文阅读优化 */
  font-size: 17px;
  line-height: 1.85; /* 更舒适的行高 */
}

.content::v-deep p {
  text-indent: 2em; /* 首行缩进2字符 */
  margin: 0.8em 0; /* 段落间距 */
  line-height: 1.85;
}

.content::v-deep br {
  content: ""; /* 优化换行显示 */
  display: block;
  margin-bottom: 0.5em;
}

/* 按钮交互优化​ */
button {
  &:hover {
    transform: translateY(-1px);
  }
}
</style>
